#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/wrap.h"

/*
	功能:判断文件是否存在
	参数：filePath：文件路径
	返回值：
		1：文件存在
		0：文件不存在
*/
int is_file_exist(const char *filePath){
	FILE *fp = fopen(filePath, "r");
	if (fp == NULL) {
		// printf("%s\n", filePath);
		return 0;
	}
	fclose(fp);
	return 1;
}
/*
	功能：将文件内容读取后追加在字符串buff后面
	参数：
		filePath:路径
		buff:要追加内容的字符串
	返回值：
		要追加内容的字符串的首地址
*/
char* read_file_after_buff(const char* filePath, char *buff){
	char buf[8] = {'\0'};
	if (is_file_exist(filePath)) {
		FILE *fp = fopen(filePath, "r");
		while (fgets(buf, sizeof(buf), fp) != NULL) {
			strcat(buff, buf);
		}
		fclose(fp);
	}
	return buff;
}

/*
	功能：根据身份发回给请求者，所有在线可即时通讯的人的id账号
	参数：identity:请求者的身份 socketfd：请求者的连接描述符
	返回值：无
	作者：ljj
	时间：2020/8/2
*/
void assrBook(int identity, int socketfd){

	char buf[16] = {'\0'};
	char buff[4096] = {'\0'};
	//命令解析标识头
	strcat(buff, "assrBook ");
	//在线列表路径
	char manager_Path[] = "../manager/online/onlineList.txt";
	char service_Path[] = "../service/online/onlineList.txt";
	char customer_Path[] = "../customer/online/onlineList.txt";
	//身份是管理员，看到所有人的在线列表
	if (identity == 0) {
		//读取文件内容缓存到buff
		strcat(buff, "\nmanager:\n");
		read_file_after_buff(manager_Path, buff);
		strcat(buff, "\nservice:\n");
		read_file_after_buff(service_Path, buff);
		strcat(buff, "\ncustomer:\n");
		read_file_after_buff(customer_Path, buff);
		//身份是客服，看到客户和客服的在线列表
	} else if (identity == 1){
		strcat(buff, "\nservice:\n");
		read_file_after_buff(service_Path, buff);
		strcat(buff, "\ncustomer:\n");
		read_file_after_buff(customer_Path, buff);
		//身份是客户，看到客服的在线列表
	} else {
		strcat(buff, "\nservice:\n");
		read_file_after_buff(service_Path, buff);		
	}

	Write(socketfd, buff, strlen(buff));
	//printf("%s\n", buff);
	//将通讯人列表发送给请求者************************socket
	//Write(socketfd, buff, strlen(buff));
}

/*
int main (){

	printf("manager request:\n");
	assrBook(0, 1);
	printf("\n");
	printf("customer request:\n");
	assrBook(1, 1);
	printf("\n");
	printf("service request:\n");
	assrBook(2, 1);
	printf("\n");

	return 0;
}*/
